package paytm

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/spf13/viper"
	"io/ioutil"
	"net/http"
	"os"
	"payment/boostrap"
	"payment/utils"
)

// PaytmOrderResponse is representing of paytm response structure
type PaytmOrderResponse struct {
	MID              string `json:"MID"`
	ORDER_ID         string `json:"ORDER_ID"`
	CUST_ID          string `json:"CUST_ID"`
	INDUSTRY_TYPE_ID string `json:"INDUSTRY_TYPE_ID"`
	CHANNEL_ID       string `json:"CHANNEL_ID"`
	TXN_AMOUNT       string `json:"TXN_AMOUNT"`
	WEBSITE          string `json:"WEBSITE"`
	CALLBACK_URL     string `json:"CALLBACK_URL"`
	EMAIL            string `json:"EMAIL"`
	MOBILE_NO        string `json:"MOBILE_NO"`
	PAYMENT_TYPE_ID  string `json:"PAYMENT_TYPE_ID"`
	CHECKSUMHASH     string `json:"CHECKSUMHASH"`
}

type TxnAmount struct {
	Value    string `json:"value"`
	Currency string `json:"currency"`
}

type UserInfo struct {
	CustId string `json:"custId"`
}

type PaytmRequest struct {
	RequestType string    `json:"requestType"`
	Mid         string    `json:"mid"`
	OrderId     string    `json:"orderId"`
	WebsiteName string    `json:"websiteName"`
	TxnAmount   TxnAmount `json:"txnAmount"`
	UserInfo    UserInfo  `json:"userInfo"`
	CallbackUrl string    `json:"callbackUrl"`
}

// Message function
func Message(status int, message string) map[string]interface{} {
	return map[string]interface{}{"status": status, "message": message}
}

// Respond common function
func Respond(w http.ResponseWriter, data map[string]interface{}) {
	w.Header().Add("Content-Type", "application/json")
	json.NewEncoder(w).Encode(data)
}

// Paytm order response function
func paytmOrderResponseFun(orderId string, custId string, mobileId string, email string, txnAmount string, website string, callbackUrl string, checksum string, channelId string, verifiedBy string, isUserVerified string, paymentModeOnly string, authMode string, paymentTypeId string) PaytmOrderResponse {
	res := PaytmOrderResponse{
		MID:              os.Getenv("PAYTM_MID"),
		ORDER_ID:         orderId,
		CUST_ID:          custId,
		INDUSTRY_TYPE_ID: os.Getenv("PAYTM_INDUSTRY_TYPE_ID"),
		CHANNEL_ID:       channelId,
		TXN_AMOUNT:       txnAmount,
		WEBSITE:          website,
		CALLBACK_URL:     callbackUrl,
		EMAIL:            email,
		MOBILE_NO:        mobileId,
		CHECKSUMHASH:     checksum,
		PAYMENT_TYPE_ID:  paymentTypeId,
	}
	return res
}

func Payment() {
	boostrap.InitConf()
	var ORDER_ID = utils.GetOrderId("PTM")
	var MOBILE_NO = "9586311403"
	var EMAIL = "xyz@gmail.com"
	var TXN_AMOUNT = "45.00"
	//var VERIFIED_BY = "MOBILE"
	//var IS_USER_VERIFIED = "YES"
	//var PAYMENT_MODE_ONLY = "YES"
	//var PAYMENT_TYPE_ID = "PPI"

	var CUST_ID = "PTMtest111"

	var channelID = viper.GetString("paytm.CHANNEL_ID")
	var website = "https://pay.jeetogame.com"

	//channelID = os.Getenv("PAYTM_CHANNEL_ID")
	//website = os.Getenv("PAYTM_WEBSITE")
	callbackUrl := "https://pay.jeetogame.com/payment_callback"
	MID := viper.GetString("paytm.MID")
	paramList := map[string]string{
		"MID":      MID,
		"ORDER_ID": ORDER_ID,
		"CUST_ID":  CUST_ID,
		//"INDUSTRY_TYPE_ID": os.Getenv("PAYTM_INDUSTRY_TYPE_ID"),
		"CHANNEL_ID":   channelID,
		"TXN_AMOUNT":   TXN_AMOUNT,
		"WEBSITE":      website,
		"CALLBACK_URL": callbackUrl,
		"EMAIL":        EMAIL,
		"MOBILE_NO":    MOBILE_NO,
		//"PAYMENT_TYPE_ID": PAYMENT_TYPE_ID,
	}
	checksum, err := GetChecksumFromArray(paramList)
	fmt.Println(checksum)
	if err != nil {
		fmt.Println("err = ", err)
	} else {
		fmt.Println("checksum", checksum)
	}

	payUrl := fmt.Sprintf("%s?mid=%v&orderId=%v", viper.GetString("paytm.TXN_URL"), MID, ORDER_ID)
	reqJson, err := json.Marshal(&PaytmRequest{
		RequestType: "Payment",
		Mid:         MID,
		OrderId:     ORDER_ID,
		WebsiteName: website,
		TxnAmount: TxnAmount{
			Value:    TXN_AMOUNT,
			Currency: "INR",
		},
		UserInfo: UserInfo{
			CustId: CUST_ID,
		},
		CallbackUrl: callbackUrl,
	})
	fmt.Println(string(reqJson))
	fmt.Println(payUrl)
	req, err := http.NewRequest("POST", payUrl, bytes.NewBuffer(reqJson))
	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("signature", checksum)
	req.Header.Set("Cache-Control", "no-cache")
	//req.Header.Set("x-forwarded-for", "103.23.28.16")
	//req.Header.Set("client-ip", "103.23.28.16")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		fmt.Println(body)
		return
	}
	fmt.Println(string(body))
	//orderResponse := paytmOrderResponseFun(ORDER_ID, CUST_ID, MOBILE_NO, EMAIL, TXN_AMOUNT, website, callbackUrl, checksum, channelID, VERIFIED_BY, IS_USER_VERIFIED, PAYMENT_MODE_ONLY, AUTH_MODE, PAYMENT_TYPE_ID)
	//fmt.Println("Response", orderResponse)
}
